﻿using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;

namespace NW
{
	class Program
	{
		static void Log(String S)
		{
			Console.WriteLine(DateTime.Now.ToString("HH:mm") + " " + S);
		}
		static void Main(string[] args)
		{
			Log("Start test server...");
			try
			{
				TestServer Srv = new TestServer(6000);

				Srv.ClientConnected += (srv, cli) => Log("Client" + cli.ToString() + " connected!");
				Srv.ClientExit += (srv, cli) => Log("Client " + cli.ToString() + " exited");
				Srv.StopPrevented += srv => Console.WriteLine("Stop prevented");
				Srv.Stopped += srv => Console.WriteLine("Stopped");
				Srv.ClientListEmpty += srv => Console.WriteLine("Client list empty");
				Srv.Start();
				Log("Server started up");
				Console.ReadKey(true);
				Srv.Stop(true);
			}
			catch (Exception e)
			{
				Log("Server error!");
				Log(e.Message);
				Log(e.StackTrace);
			}
			Console.ReadKey(true);
		}
	}
	class TestServer : NWServer
	{
		public TestServer(int port)
			: base(port)
		{

		}
		protected override NWClient MakeClient(TcpClient C)
		{
			return new ServerClient(C);
		}
	}
	class ServerClient : NWClient
	{
		public ServerClient(TcpClient C)
			: base(C)
		{
			ExitReceived += x =>
			{
				Console.WriteLine("SRV_CLI: Exit received");
			};
		}
		protected override bool _ProcessMessage()
		{
			int N = FetchInt32();
			Console.WriteLine("MGS #" + N);
			Console.WriteLine("Length: " + MsgBuf.Length);
			Console.WriteLine("Data:");
			int Col = 0;
			while (MsgPtr < MsgBuf.Length)
			{
				Col++;
				byte B = FetchByte();
				Console.Write(B.ToString("X2"));
				if (Col % 8 == 0)
					Console.WriteLine();
				else if (MsgPtr < MsgBuf.Length)
					Console.Write("-");
			}
			if (Col % 8 != 0)
				Console.WriteLine();
			return true;
		}
	}
}